package com.zzb.framework.modules.param.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.zzb.framework.cache.CacheComponent;
import com.zzb.framework.common.BaseResponse;
import com.zzb.framework.common.BaseService;
import com.zzb.framework.common.FrameworkException;
import com.zzb.framework.modules.event.EventHome;
import com.zzb.framework.modules.param.dao.SysParamDAO;
import com.zzb.framework.modules.param.entity.SysParam;
import com.zzb.framework.modules.param.event.SysParamChangeEvent;
import com.zzb.framework.modules.role.entity.SysUserEntity;
import com.zzb.framework.utils.StringToTTypeUtil;
import com.zzb.framework.validator.annotation.ValidatorEnabled;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 系统配置表 service类
 */
@Service("sysParamService")
public class SysParamService extends BaseService<SysParamDAO, SysParam> {
    private static final Logger logger = LoggerFactory.getLogger(SysParamService.class);
    @Autowired
    private CacheComponent cacheComponent;
    @Autowired
    private SysParamDAO sysParamDAO;

    @Override
    public SysParamDAO getDAO() {
        return sysParamDAO;
    }

    /**
     * 删除系统配置表
     */
    @Transactional
    public BaseResponse deleteSysParam(String [] ids, SysUserEntity operate) throws FrameworkException {

        return deleteByIds(Lists.newArrayList(ids));
    }

    /**
     * 保存系统配置表
     */
    @ValidatorEnabled
    public BaseResponse<SysParam> saveSysParam(SysParam sysParam, SysUserEntity operator) throws FrameworkException {
        //同时加入缓存
        cacheComponent.put("PARAM", sysParam.getParamKey(), sysParam, 0L);
        logger.info("正在保存系统配置表[" + JSON.toJSONString(sysParam) + "][" + JSON.toJSONString(operator) + "]");

        BaseResponse<SysParam> sysParamBaseResponse = insertOrUpdate(sysParam, operator);
        if(sysParamBaseResponse.isSuccess()){
            //发布配置表变更事件
            EventHome.publishEvent(new SysParamChangeEvent(sysParam));
        }
        return sysParamBaseResponse;
    }

    /**
     * 获取参数值，如果没有找到配置，则返回空
     */
    public <T> T get(String paramName, Class<T> clazz) {
        //同时加入缓存
        SysParam sysParam = cacheComponent.get("PARAM", paramName, SysParam.class);
        if (sysParam == null) {
            sysParam = getDAO().findTopByParamKey(paramName);
        }
        return sysParam != null ? StringToTTypeUtil.convert(sysParam.getParamValue(), clazz) : null;
    }

    /**
     * 获取参数值，如果没有找到配置，则返回默认值
     */
    public <T> T get(String paramName, Class<T> clazz, T defaultValue) {
        SysParam sysParam = cacheComponent.get("PARAM", paramName, SysParam.class);
        if (sysParam == null) {
            sysParam = getDAO().findTopByParamKey(paramName);
        }
        return sysParam != null ? StringToTTypeUtil.convert(sysParam.getParamValue(), clazz) : defaultValue;
    }


    public SysParam findTopByParamKey(String paramName) {
        return getDAO().findTopByParamKey(paramName);
    }

    /**
     * 获取参数值
     */
    public String getString(String paramName, String defaultValue) {
        SysParam sysParam = cacheComponent.get("PARAM", paramName, SysParam.class);
        if (sysParam == null) {
            sysParam = getDAO().findTopByParamKey(paramName);
        }
        return sysParam != null ? sysParam.getParamValue() : defaultValue;
    }

    /**
     * 查看所有公开的配置
     * @return
     */
    public Map<String,String> selectAllOvertMap(){
        List<SysParam> params = getDAO().getMapper().selectList(new QueryWrapper<SysParam>().eq("overt", 1));
        return params.stream().collect(Collectors.toMap(SysParam::getParamKey,SysParam::getParamValue));
    }

    public <T> T getJSONObject(String paramName , Class<T> clazz){
        String value = getString(paramName,"");
        if(StringUtils.isNotBlank(value)){
            return JSON.parseObject(value, clazz);
        }

        try {
            return clazz.newInstance();
        } catch (Exception e) {
            throw new FrameworkException("获取参数失败");
        }

    }

}
